package com.warehouse.dao.impl;

import com.warehouse.dao.WarehouseDao;
import com.warehouse.dao.common.HibernateUtil;
import com.warehouse.entity.Cargo;
import com.warehouse.entity.Warehouse;
import org.hibernate.Query;

import java.util.List;

public class WarehouseDaoImpl implements WarehouseDao {
    @Override
    public int add(Warehouse warehouse) {
        try {
            HibernateUtil.currentSession().save(warehouse);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public int update(Warehouse warehouse) {
        try {
            HibernateUtil.currentSession().update(warehouse);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public int delete(int id) {
        try {
            //先获取id
            Warehouse warehouse = (Warehouse) HibernateUtil.currentSession().get(Warehouse.class, id);
            HibernateUtil.currentSession().delete(warehouse);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public List<Warehouse> allPage(int startPage, int pageSize) {
        Query query = HibernateUtil.currentSession().createQuery("from Warehouse");
        return query.list();
    }

    @Override
    public List<Warehouse> all(){
        Query query = HibernateUtil.currentSession().createQuery("from Warehouse");
        return query.list();
    }

    @Override
    public int count() {
        return HibernateUtil.currentSession().createQuery("from Warehouse").list().size();
    }

    @Override
    public Warehouse byId(int id) {
        Warehouse warehouse = (Warehouse) HibernateUtil.currentSession().get(Warehouse.class, id);
        return warehouse;
    }

    @Override
    public List<Warehouse> byAdminNum(int startPage, int pageSize, String area) {
        Query query = HibernateUtil.currentSession().createQuery("from Warehouse w where w.area like '%" + area + "%'");
        query.setFirstResult(startPage);
        query.setMaxResults(pageSize);
        return query.list();
    }

    @Override
    public int countByAdminNum(String area) {
        return HibernateUtil.currentSession().createQuery("from Warehouse w where w.area like '%" + area + "%'").list().size();
    }
}
